#include "power.h"
#include "system_cw32l010.h"
#include "cw32l010_gpio.h"
#include "cw32l010_adc.h"
#include "rda5807m.h"
#include "cw32l010_sysctrl.h"
#include "cw32l010_systick.h"
#include "cw32l010_lptim.h"

void POWER_2V8_INIT(void)
{
    GPIO_InitTypeDef GPIO_InitStructure = {0};
    GPIO_InitStructure.Pins = GPIO_PIN_1;
    GPIO_InitStructure.Mode = GPIO_MODE_OUTPUT_PP;
    GPIO_Init(CW_GPIOB, &GPIO_InitStructure);
    // 音乐
    GPIO_InitStructure.Pins = GPIO_PIN_3;
    GPIO_InitStructure.Mode = GPIO_MODE_OUTPUT_PP;
    GPIO_Init(CW_GPIOA, &GPIO_InitStructure);
    PA03_SETLOW();
}
void POWER_Battery_INIT(void)
{
    __SYSCTRL_ADC_CLK_ENABLE();
    ADC_InitTypeDef ADC_InitStructure = {0};
    ADC_InitStructure.ADC_ClkDiv = ADC_Clk_Div8;                   // ADCCLK = PCLK/8 = 1MHz
    ADC_InitStructure.ADC_ConvertMode = ADC_ConvertMode_Once;      // 单次采样
    ADC_InitStructure.ADC_SQREns = ADC_SqrEns0to0;                 // 单通道
    ADC_InitStructure.ADC_IN0.ADC_InputChannel = ADC_InputVref1P2; // 采内部BGR1.2V，反推MCU供电电压VDD
    ADC_InitStructure.ADC_IN0.ADC_SampTime = ADC_SampTime390Clk;   //// 采样TS和BGR时需要保证采样时间至少40uS, 因此采样时钟至少 = 40uS / (1/1MHz) = 40个
    ADC_Init(&ADC_InitStructure);
    CW_ADC->CR_f.BGREN = 1; // 使能BGR1.2V ，内部BGR的启动时间大约为30μs
    SysTickDelay(1);        // 在此延时1ms
    ADC_ClearITPendingAll();
    // ADC使能
    ADC_Enable();
}
//低功耗定时器
void LPTIM_Configuration(void)
{
    LPTIM_InitTypeDef LPTIM_InitStruct = {0};  
    
    LPTIM_InitStruct.LPTIM_ClockSource = LPTIM_CLOCK_SOURCE_MCLK;
    LPTIM_InitStruct.LPTIM_CounterMode = LPTIM_COUNTER_MODE_TIME;
    LPTIM_InitStruct.LPTIM_Period = 32800-1;
    LPTIM_InitStruct.LPTIM_Prescaler = LPTIM_PRS_DIV2;
    LPTIM_Init(&LPTIM_InitStruct);
    
    SYSCTRL_LSI_Enable();    // 使用LSI作为时钟源  
    LPTIM_InternalClockConfig(LPTIM_ICLK_LSI);

    LPTIM_ITConfig(LPTIM_IT_ARRM, ENABLE);
    CW_LPTIM->ICR = 0x00;
	NVIC_EnableIRQ(LPTIM_IRQn);
    
    LPTIM_Cmd(ENABLE);   
    //设置连续运行
    LPTIM_SelectOnePulseMode(LPTIM_OPERATION_REPETITIVE);    
}

void POWER_GET_BATTERY(void)
{
    uint16_t valueAdc, BGR_1_2V_value;
    ADC_SoftwareStartConvCmd(ENABLE);
    // ADC_Enable();
    while (!(CW_ADC->ISR & ADC_ISR_EOC_Msk))
        ;
    ADC_ClearITPendingBit(ADC_IT_EOC);
    valueAdc = ADC_GetConversionValue(0);
    BGR_1_2V_value = *((uint16_t *)0x001007D2);
    fm_info.battery = (4095 * BGR_1_2V_value * 0.001f) / valueAdc;
}
//进入深度睡眠
void POWER_DeepSleep(void){
    //关闭SPI时钟
    SYSCTRL_APBPeriphReset1(SYSCTRL_APB1_PERIPH_SPI, DISABLE);
    //关闭ADC时钟
    SYSCTRL_APBPeriphReset1(SYSCTRL_APB1_PERIPH_ADC, DISABLE);
    SYSCTRL_APBPeriphClk_Enable1(SYSCTRL_APB1_PERIPH_SPI, DISABLE);
    SYSCTRL_APBPeriphClk_Enable1(SYSCTRL_APB1_PERIPH_ADC, DISABLE);
    //关闭I2C时钟
    SYSCTRL_APBPeriphReset2(SYSCTRL_APB2_PERIPH_I2C, DISABLE);
    SYSCTRL_APBPeriphClk_Enable2(SYSCTRL_APB2_PERIPH_I2C, DISABLE);
    SYSCTRL_GotoDeepSleep();
}
void POWER_WAKEUP(void){

}